package liill1.uuzgtq16;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.dynamicallyacquired.BuildConfig;
import liill1.qyhuyg07.DataPoint;
import com.dynamicallyacquired.R;
import liill1.js_interface.AdjustToJavascript;
import liill1.js_interface.AppsflyerToJavascript;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.toast.Toaster;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class iujhjh2 extends AppCompatActivity  {
    private WebView webView;
    private ProgressBar progressBar;

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @SuppressLint({"SetJavaScriptEnabled","ClickableViewAccessibility"})
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        webView = findViewById(R.id.myWebview);
        progressBar = findViewById(R.id.progressBar);
        FloatingActionButton fab = findViewById(R.id.float_collection);

        fab.setOnTouchListener(new View.OnTouchListener() {
            private float initialX, initialY;
            private float initialTouchX, initialTouchY;
            private final int screenWidth = getResources().getDisplayMetrics().widthPixels;
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        initialX = view.getX();
                        initialY = view.getY();
                        initialTouchX = event.getRawX();
                        initialTouchY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float deltaX = event.getRawX() - initialTouchX;
                        float deltaY = event.getRawY() - initialTouchY;
                        float newX = initialX + deltaX;
                        float newY = initialY + deltaY;
                        newX = Math.max(0, Math.min(newX, screenWidth - view.getWidth()));
                        newY = Math.max(0, Math.min(newY, getResources().getDisplayMetrics().heightPixels - view.getHeight()));
                        view.setX(newX);
                        view.setY(newY);
                        return true;
                    case MotionEvent.ACTION_UP:
                        float center = screenWidth / 2f;
                        float finalX = view.getX() + view.getWidth() / 2f > center ? screenWidth - view.getWidth() : 0;
                        view.animate()
                                .x(finalX)
                                .setDuration(200)
                                .start();

                        if (Math.abs(event.getRawX() - initialTouchX) < 10 && Math.abs(event.getRawY() - initialTouchY) < 10) {
                            view.performClick();
                        }
                        return true;
                }
                return false;
            }
        });
        fab.performClick();
        fab.setOnClickListener(view -> {
            final BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(iujhjh2.this);
            bottomSheetDialog.setContentView(R.layout.bottom_sheet_menu);
            bottomSheetDialog.show();

            TextView goHome = bottomSheetDialog.findViewById(R.id.go_home);
            TextView exitApp = bottomSheetDialog.findViewById(R.id.exit_app);

            if (goHome != null) {
                goHome.setOnClickListener(v -> {
                    bottomSheetDialog.dismiss();
                    webView.loadUrl(BuildConfig.Url);
                    webView.clearHistory();
                    canExit = true;
                });
            }

            if (exitApp != null) {
                exitApp.setOnClickListener(v -> {
                    bottomSheetDialog.dismiss();
                    finish();
                });
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress < 100 && progressBar.getVisibility() == ProgressBar.GONE) {
                    progressBar.setVisibility(ProgressBar.VISIBLE);
                }
                progressBar.setProgress(newProgress);
                if (newProgress == 100) {
                    progressBar.setVisibility(ProgressBar.GONE);
                }
            }
        });
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(request.getUrl().toString());
                return false;
            }
        });
        WebSettings settings = webView.getSettings();
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        CookieManager.getInstance().setAcceptThirdPartyCookies(webView, false);
        settings.setJavaScriptEnabled(true);
        String propertyValue = BuildConfig.Url;
        System.out.println(propertyValue);
        String dataPointsJson = BuildConfig.dataPointType;
        Type listType = new TypeToken<List<DataPoint>>() {}.getType();

        // 使用Gson反序列化JSON到List<DataPoint>
        List<DataPoint> dataPoints = new Gson().fromJson(dataPointsJson, listType);
        Map<Double, List<DataPoint>> groupedByDataTypeId = dataPoints.stream()
                .collect(Collectors.groupingBy(DataPoint::getDataTypeId));
        if (groupedByDataTypeId.get(1.0) != null){
            webView.addJavascriptInterface(new AdjustToJavascript(), "Android");
        }else {
            webView.addJavascriptInterface(new AppsflyerToJavascript(this), "Android");
        }
        webView.loadUrl(propertyValue);
    }
    private long lastBackPressTime = 0;
    private boolean canExit = false;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            if (canExit){
                long currentTime = System.currentTimeMillis();
                if (currentTime - lastBackPressTime < 2000) {
                    canExit = false;
                    return super.onKeyDown(keyCode, event);
                } else {
                    canExit = false;
                    lastBackPressTime = currentTime;
                    Toaster.show("再按一次返回退出应用");
                    return false;
                }
            }else {
                webView.goBack();
            }
            return true;
        }else {
            canExit = false;
            long currentTime = System.currentTimeMillis();
            if (currentTime - lastBackPressTime < 2000) {
                return super.onKeyDown(keyCode, event);
            } else {
                lastBackPressTime = currentTime;
                Toaster.show("再按一次返回退出应用");
                return false;
            }
        }
    }


}
